<template>
  <div class="user-management-page">
    <!-- 头部 -->
    <div class="header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">用户管理</h1>
          <div class="divider"></div>
          <span class="subtitle">Total: {{ totalItems }}</span>
        </div>
        <div class="action-group">
          <el-input
            v-model="searchKeyword"
            placeholder="输入用户名/昵称"
            clearable
            @input="handleSearch"
            class="search-input"
            size="large"
          >
            <template #prefix>
              <el-icon class="search-icon"><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" size="large" @click="addUser">新增用户</el-button>
        </div>
      </div>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <el-table :data="pageData" stripe style="width: 100%">
        <el-table-column prop="id" label="用户ID" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="nickname" label="昵称" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="mobile" label="电话" />
        <el-table-column label="创建人" width="120">
          <template #default="{row}">
            {{ getCreatorName(row.createBy) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{row}">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="更新人" width="120">
          <template #default="{row}">
            {{ getUpdaterName(row.updateBy) }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="180">
          <template #default="{row}">
            {{ formatTime(row.updateTime) }}
          </template>
        </el-table-column>
        
                <!-- 新增状态切换列 -->
                <el-table-column label="状态" width="200">
          <template #default="{row}">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="updateUserStatus(row)"
              active-text="启用"
              inactive-text="停用"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            />
          </template>
        </el-table-column>

        


        <el-table-column label="操作" fixed="right" width="250">
          <template #default="scope">
            <el-button size="small" @click="editUser(scope.row)">编辑</el-button>
            <el-button size="small" type="info" @click="assignRoles(scope.row)">
              分配角色
            </el-button>
            <el-button size="small" type="danger" @click="openResetPasswordDialog(scope.row)">
              重置密码
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[20, 50, 100, 200]"
        :total="totalItems"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑用户' : '新增用户'"
      width="600px"
      :close-on-click-modal="false"
    >
          <el-form
            ref="userFormRef"
            :model="formData"
            :rules="formRules"
            label-width="100px"
            label-position="left"
          >
        <el-form-item label="用户名：" prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
          <!-- 新增密码输入框（仅限新增模式） -->
        <el-form-item v-if="!isEditMode" label="密码：" prop="password">
          <el-input
            type="password"
            v-model="formData.password"
            placeholder="请输入密码"
            show-password
            clearable
          />
        </el-form-item>

        <!-- 新增密码确认输入框 -->
        <el-form-item v-if="!isEditMode" label="确认密码：" prop="confirmPassword">
          <el-input
            type="password"
            v-model="formData.confirmPassword"
            placeholder="请再次输入密码"
            show-password
            clearable
          />
        </el-form-item>
        <el-form-item label="昵称：" prop="nickname">
          <el-input
            v-model="formData.nickname"
            placeholder="请输入昵称"
            clearable
          />
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input
            v-model="formData.email"
            placeholder="请输入邮箱"
            clearable
          />
        </el-form-item>
        <el-form-item label="手机号：" prop="mobile">
          <el-input
            v-model="formData.mobile"
            placeholder="请输入手机号"
            clearable
          />
        </el-form-item>
        
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            {{ isEditMode ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="resetPasswordDialogVisible"
      title="密码重置"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="resetPasswordFormRef"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="新密码：" prop="newpassword">
          <el-input
            type="password"
            v-model="resetPasswordForm.newpassword"
            clearable
          />
        </el-form-item>
        <el-form-item label="再次输入：" prop="repeatpassword">
          <el-input
            type="password"
            v-model="resetPasswordForm.repeatpassword"
            clearable
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleResetPassword">重置</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed,onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import {
  getUsers,
  createUser as createUserApi,
  updateUser as updateUserApi,
  resetPassword as resetPasswordApi,
  updateUserStatus as updateUserStatusApi
} from '@/api/userApi'
import dayjs from 'dayjs'
import { useUserStore } from '@/stores/userStore'
const userStore = useUserStore() // 初始化 Store

const router = useRouter()

// 对话框控制
const dialogVisible = ref(false)
const isEditMode = ref(false)
const userFormRef = ref(null)
const resetPasswordDialogVisible = ref(false)
const resetPasswordFormRef = ref(null)

// 表单数据
const formData = reactive({
  id: '',
  username: '',
  password: '',         // 密码字段
  confirmPassword: '',  // 新增确认密码字段
  nickname: '',
  email: '',
  mobile: ''
})

// 重置密码表单
const resetPasswordForm = reactive({
  newpassword: '',
  repeatpassword: ''
})

// 验证规则
const formRules = computed(() => {
  const baseRules = {
    username: [
      { required: true, message: '用户名不能为空', trigger: 'blur' },
      { min: 2, max: 16, message: '长度在2到16个字符', trigger: 'blur' }
    ],
    nickname: [
      { required: true, message: '昵称不能为空', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
    ],
    email: [
      { required: true, message: '邮箱不能为空', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    mobile: [
      { required: true, message: '手机号不能为空', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ]
  }

  // 仅在创建模式添加密码规则
  if (!isEditMode.value) {
    baseRules.password = [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
    ]
    baseRules.confirmPassword = [
      { required: true, message: '请确认密码', trigger: 'blur' },
      { 
        validator: (rule, value, callback) => {
          if (value !== formData.password) {
            callback(new Error('两次输入的密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur' 
      }
    ]
  }

  return baseRules
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)
const totalItems = ref(0)
const pageData = ref([])
const allData = ref([])
const searchKeyword = ref('')
const userMap = ref({})

// 加载用户数据
const loadUsers = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }
    const response = await getUsers(params)
    allData.value = response.data.content || []
    filterData()
    totalItems.value = response.data.total || 0
  } catch (error) {
    ElMessage.error('数据加载失败')
    console.error(error)
  }
}


const loadAllUsers = async () => {
  try {
    const res = await getUsers({ page: 1, size: 1000 }) // 根据实际情况调整size
    res.data.content.forEach(user => {
      userMap.value[user.id] = user.nickname
    })
  } catch (error) {
    console.error('用户数据加载失败', error)
  }
}

// 获取创建人昵称
const getCreatorName = (userId) => {
  return userMap.value[userId] || '未知'
}

// 获取更新人昵称
const getUpdaterName = (userId) => {
  return userMap.value[userId] || '未知'
}

// 时间格式化
const formatTime = (time) => {
  // 处理空值和日期对象两种格式
  if (!time) return '-'
  try {
    return dayjs(time).isValid() 
      ? dayjs(time).format('YYYY-MM-DD HH:mm')
      : '-'
  } catch (e) {
    return '-'
  }
}

// 数据过滤
const filterData = () => {
  if (searchKeyword.value === '') {
    pageData.value = allData.value
  } else {
    pageData.value = allData.value.filter(item => {
      return item.username.includes(searchKeyword.value) || 
             item.nickname.includes(searchKeyword.value)
    })
  }
}

// 状态更新
const updateUserStatus = async (user) => {
  try {
    await updateUserStatusApi(user.id, { status: user.status })
    ElMessage.success('状态更新成功')
    loadUsers()
  } catch (error) {
    ElMessage.error('状态更新失败: ' + (error.response?.data?.message || '未知错误'))
    user.status = user.status === 1 ? 0 : 1 // 回滚状态
  }
}

// 搜索处理
let searchTimer = null
const handleSearch = () => {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    filterData()
  }, 300)
}

// 分页处理
const handlePageChange = (newPage) => {
  currentPage.value = newPage
  loadUsers()
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  loadUsers()
}

// 打开新增对话框
const addUser = () => {
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

// 打开编辑对话框
const editUser = (user) => {
  isEditMode.value = true
  Object.assign(formData, {
    id: user.id,
    username: user.username,
    nickname: user.nickname,
    email: user.email,
    mobile: user.mobile,
  })
  dialogVisible.value = true
}

// 重置密码
const openResetPasswordDialog = (user) => {
  resetPasswordDialogVisible.value = true
  resetPasswordForm.newpassword = ''
  resetPasswordForm.repeatpassword = ''
  selectedUserForReset = user
}

const handleResetPassword = async () => {
  try {
    await resetPasswordFormRef.value.validate()

    if (resetPasswordForm.newpassword !== resetPasswordForm.repeatpassword) {
      ElMessage.error('两次输入的密码不一致')
      return
    }

    const selectedUser = selectedUserForReset
    const passwordData = { password: resetPasswordForm.newpassword }
    await resetPasswordApi(selectedUser.id, passwordData)
    ElMessage.success('密码重置成功')
    resetPasswordDialogVisible.value = false
    loadUsers()
  } catch (error) {
    ElMessage.error('密码重置失败: ' + (error.response?.data?.message || '未知错误'))
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    console.log("准备提交数据")
    console.log('userStore.userId:', userStore.userId)


    
    // 显式调用验证并捕获错误详情
    try {
      await userFormRef.value.validate()
    } catch (error) {
      console.error('表单验证失败详情:', error)
      error.fields.forEach(field => {
        console.error(`字段 ${field.fullField} 验证失败:`, field.message)
      })
      ElMessage.error('表单验证失败：' + error.fields[0].message)
      return
    }
    
    console.log('userStore.userId:', userStore.userId)
    const currentUserId = parseInt(userStore.userId, 10)
    if (isNaN(currentUserId)) {
      ElMessage.error('用户信息异常，请重新登录')
      return
    }

    // 构建提交数据（创建时包含密码）
    const submitData = { 
      ...formData,
      updateBy: currentUserId,
      createBy: currentUserId
    }
    
    // 编辑模式移除密码字段
    if (isEditMode.value) {
      delete submitData.password
      delete submitData.confirmPassword
    }

    console.log("最终提交数据:", submitData)
    
    // API调用
    if (isEditMode.value) {
      await updateUserApi(submitData)
      ElMessage.success('更新成功')
    } else {
      await createUserApi(submitData)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    loadUsers()
  } catch (error) {
    console.error('提交错误:', error)
    const errorMsg = error.response?.data?.message || '操作失败'
    ElMessage.error(errorMsg)
  }
}

// 分配角色
const assignRoles = (user) => {
  router.push({
    name: 'user-role-assignment',
    params: { userId: user.id }
  })
}

// 重置表单
const resetForm = () => {
  userFormRef.value?.resetFields()
  Object.assign(formData, {
    id: '',
    username: '',
    nickname: '',
    email: '',
    mobile: ''
  })
}


onMounted(async () => {
  await loadAllUsers() // 先加载全量用户
  loadUsers()          // 再加载分页数据
  updateTableContainerHeight()
  window.addEventListener('resize', updateTableContainerHeight)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', updateTableContainerHeight)
})

const updateTableContainerHeight = () => {
  const headerHeight = document.querySelector('.header')?.offsetHeight || 0
  const paginationHeight = document.querySelector('.pagination-container')?.offsetHeight || 0
  const padding = 40
  const tableContainer = document.querySelector('.table-container')
  if (tableContainer) {
    tableContainer.style.height = `calc(100vh - ${headerHeight + paginationHeight + padding}px)`
  }
}

let selectedUserForReset = null
</script>

<style scoped>
.user-management-page {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  padding: 10px 10px;
  border-bottom: 1px solid #e2e8f0;
  flex-shrink: 0;
}

.header-content {
  max-width: 1440px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 5px;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 24px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
  letter-spacing: 0.5px;
}

.subtitle {
  color: #64748b;
  font-size: 14px;
}

.divider {
  width: 2px;
  height: 24px;
  background: #cbd5e1;
}

.action-group {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-input {
  width: 320px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.table-container {
  flex: 1;
  padding: 5px 0px;
  overflow-y: auto;
  background: #ffffff;
}

:deep(.el-table) {
  --el-table-border-color: #e2e8f0;
  --el-table-header-bg-color: #f8fafc;
  --el-table-row-hover-bg-color: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

:deep(.el-table th) {
  font-weight: 600;
  color: #475569;
}

:deep(.el-table td) {
  color: #475569;
}

.pagination-container {
  padding: 16px 32px;
  background: rgba(255, 255, 255, 0.9);
  border-top: 1px solid #e2e8f0;
  flex-shrink: 0;
}

.dialog-footer {
  text-align: right;
}

.el-form {
  padding: 20px 30px;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-input {
  width: 100%;
  max-width: 400px;
}

.el-table {
  margin: 0;
}

.el-button + .el-button {
  margin-left: 12px;
}

/* 表格容器样式 */
.table-container {
  max-height: calc(100vh - 400px); /* 可根据需要调整高度 */
  overflow-y: auto;
  margin: 20px 0;
  box-sizing: border-box;
}
</style>    